<?php

namespace Iwesen\Sem\Track\Advertisers;

use Illuminate\Support\Facades\Log;

class Baidu
{
    protected $api =  "https://ocpc.baidu.com/ocpcapi/api/uploadConvertData";

    public function callback($param)
    {
        if(!isset($param['token']) || !$param['token']){
            $param['token'] = config('sem-track.baidu.token');
            if(!$param['token']){
                throw new \Exception( 'token is not a exist !');
            }
        }
        if(!isset($param['conversionTypes']) || !is_array($param['conversionTypes'])){
            throw new \Exception( 'conversionTypes is not a exist !');
        }
        //验证转化类型并补全
        foreach($param['conversionTypes'] as $k=>$cv){
            if(!is_array($cv)){
                throw new \Exception( 'conversionTypes presentation error !'); 
            }
            if(!isset($cv['newType'])||!$cv['newType']){
                $param['conversionTypes'][$k]['newType']=config('sem-track.baidu.newType');
            }
        }
        try {
            $result = (new Request())->_request($this->api,'',$param);
            $data = json_decode($result,true);
            $status = $data['header']['status'];
            if ($status === 0) {
                return 'success';
            }
            return $data['header']['desc'];
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        } 
    }
}